package com.dstats.network;

import com.google.gson.GsonBuilder;
import com.google.gson.internal.bind.DateTypeAdapter;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Date;
import java.util.Iterator;

public class JsonReader {
    private JSONObject jsonObject;

    public JsonReader(JSONObject json) {
       jsonObject = json;
    }

    public JsonReader(String s) {
        try {
            jsonObject = new JSONObject(s);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    public JsonReader() {

    }

    public JsonReader getJsonObject(String memberName) {
        try {
            return new JsonReader(jsonObject.getJSONObject(memberName));
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return null;
    }

    public <T> T getObject(String memberName, Class<T> classOfT)  {
        String str = "";
        try {
        if (classOfT.isArray()) {
            if(memberName.isEmpty()) {
                str ="[";
                Iterator<String> iterator = jsonObject.keys();
                while (iterator.hasNext()) {
                    str += jsonObject.getJSONObject(iterator.next()).toString() ;
                    if (iterator.hasNext()){
                        str += ", ";
                    }
                }

                str += "]";
            } else {
                str = jsonObject.getJSONArray(memberName).toString();
            }
        } else {
            str = jsonObject.getJSONObject(memberName).toString();
        }

        } catch (JSONException e) {
            e.printStackTrace();
        }
        GsonBuilder gson = new GsonBuilder();
        gson.registerTypeAdapter(Date.class, new DateTypeAdapter());
        return gson.create().fromJson(str, classOfT);
    }
}
